package com.dragon.sso.controller;

import com.alibaba.fastjson.JSON;
import com.dragon.sso.dto.UserInfo;
import com.dragon.sso.ldap.LDAPConnector;
import com.novell.ldap.LDAPAttribute;
import com.novell.ldap.LDAPException;
import java.util.Optional;
import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author bin.wei
 */
@RestController
@RequestMapping("/userInfo")
@Slf4j
public class UserInfoController {

  private static final String TAG = "UserInfo Endpoint: ";

  @Resource
  private LDAPConnector ldapConnector;

  @RequestMapping
  public UserInfo getUserInfo(Authentication authentication) throws LDAPException {
    String username = authentication.getName();
    UserInfo userInfo = new UserInfo();
    ldapConnector.searchOnePerson(username, ldapEntry -> {
      String displayName = Optional.of(ldapEntry.getAttribute("displayName"))
          .orElse(new LDAPAttribute()).getStringValue();
      String email = Optional.of(ldapEntry.getAttribute("mail")).orElse(new LDAPAttribute())
          .getStringValue();
      userInfo.setName(username);
      userInfo.setDisplayName(displayName);
      userInfo.setEmail(email);

    });

    if (log.isDebugEnabled()) {
      log.debug(TAG + "userinfo \n{}", JSON.toJSONString(userInfo));
    }
    return userInfo;
  }

}
